package managedbean;


import java.io.Serializable;
import java.util.*;

import javax.ejb.EJB;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;

import jpa.CustomerJPA;
import ejb.OrderFacadeRemote;


/**
 * Managed Bean TotalAmountByCustomerMBean
 */
@ManagedBean(name = "totalAmount")
@SessionScoped
public class TotalAmountByCustomerMBean implements Serializable {

	private static final long serialVersionUID = 1L;	
	
	@EJB
	private OrderFacadeRemote orderFR;
	protected float totalAmount;
	protected CustomerJPA customer;
	
	public TotalAmountByCustomerMBean() throws Exception  {
		ListTotalAmountOrders();
	}
	
	public TotalAmountByCustomerMBean(CustomerJPA customer) throws Exception {
		customer=customer;
		ListTotalAmountOrdersCustomer(customer);	
	}
		
	public String ListTotalAmountOrders() throws Exception {
		try {
			FacesContext fc = FacesContext.getCurrentInstance();
			String customerId = getCustomerId(fc);
			ShowClientMBean sc = new ShowClientMBean(customerId);
			customer=sc.getDataCustomer();
			totalAmount=Amount(customer);
			return "TotalOrderAmountByCustomerView";
		}
		catch (Exception e) {
			e.printStackTrace();
			return "ErrorView";
		}
	}
	
	public String ListTotalAmountOrdersCustomer(CustomerJPA customer) throws Exception {
			totalAmount=Amount(customer);
			return "TotalOrdersByCustomerView";
	}
	
	public String getCustomerId(FacesContext fc){
 		Map<String,String> params = fc.getExternalContext().getRequestParameterMap();
 		return (params.get("idCustomer"));
 	}
	
	public float getTotalAmount() {
		return totalAmount;
	}

	public CustomerJPA getCustomer() {
		return customer;
	}

	@SuppressWarnings("unchecked")
	public float Amount(CustomerJPA customer) throws Exception {	
		Properties props = System.getProperties();
		Context ctx = new InitialContext(props);
		orderFR = (OrderFacadeRemote) ctx.lookup("java:app/PracticalCaseStudyJEE.jar/OrderFacadeBean!ejb.OrderFacadeRemote");
		totalAmount = (float)orderFR.amount(customer);
		return totalAmount;
		
	}
	
	
}
